﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using CDOP.Properties;
using CDOP.Utility;

namespace CDOP.Model
{
    [ScaffoldTable(false)]
    public partial class Authentication
    {
        private readonly CDOPEntities _db = new CDOPEntities();

        public bool IsUserNameExist(string userName)
        {
            var userCount = _db.Authentication.Where(x => x.User_Name == userName).Count();
            return userCount > 0;
        }

        public Authentication GetAuthenticationByUserName(string userName)
        {
            var authentiaction = _db.Authentication.Where(x => x.User_Name == userName).FirstOrDefault();
            return authentiaction;
        }

        public bool SaveAuthentication(Authentication authToSave)
        {
            try
            {
                if (authToSave.id == 0)
                    _db.AddToAuthentication(authToSave);
                else if (authToSave.id > 0)
                {
                    //_db.ObjectStateManager.ChangeObjectState(authToSave, EntityState.Modified);
                    _db.UpdateEntityObject(authToSave);
                }
                _db.SaveChanges();
                if (authToSave.id > 0)
                    return true;
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool UpdatePassword(string userName, string password)
        {
            try
            {
                var auth = _db.Authentication.Where(x => x.User_Name == userName).FirstOrDefault();
                if (auth != null)
                    auth.Password = Helper.Encrypt(password);
                _db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }



        public string CreateResetPasswordBody(Authentication auth)
        {
            var encryptedUserName = Helper.Encrypt(auth.User_Name);
            var encoded = Helper.EncodeUrl(encryptedUserName);
            var url = string.Format("{0}/ResetPassword.aspx?id={1}", Settings.Default.CurrentUrl, encoded);
            var body = string.Format(Settings.Default.EmailBody, url);
            return body;
        }
    }
}